﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CapstoneMockup.Data;
using CapstoneMockup.ViewModels;
using Expense = CapstoneMockup.Data.Expense;
using Location = Microsoft.Phone.Controls.Maps.Platform.Location;


namespace CapstoneMockup.ViewModels
{
    public partial class MainPivotPage : PhoneApplicationPage
    {
        private Timestamps _currentTimeStamp;
        
        public MainPivotPage()
        {
            InitializeComponent();
            FillInInformationFromUser();
            Loaded += FillInInformationFromUser;

            DataContext = App.ViewModel;
            bingMap.LogoVisibility = Visibility.Collapsed;
            bingMap.CopyrightVisibility = Visibility.Collapsed;

            App.ViewModel.PostLoadComplete += PostLoadCompleted;

            bingMap.LogoVisibility = Visibility.Collapsed;
            bingMap.CopyrightVisibility = Visibility.Collapsed;
            try
            {
                bingMap.Children.Add(App.GpsModel.MyRouteLayer);
            }
            catch (Exception)
            {
            }

            App.GpsModel.GeoCoordinateWatcher.PositionChanged += GeoCoordinateWatcherPositionChanged;

            if (App.GpsModel.GeoCoordinateWatcher.Status == GeoPositionStatus.Ready)
                OriginLocation.Location = App.GpsModel.FirstPosition;

        }

        public void FillInInformationFromUser()
        {
            FillMainPageInfo();
            FillHoursPageInfo();
            FillExpensesPageInfo();

            if (_currentTimeStamp != null)
            {
                ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                ClockIn.Content = "Clock Out";
            }
        }

        public void FillInInformationFromUser(Object sender, RoutedEventArgs e)
        {
            FillMainPageInfo();
            FillHoursPageInfo();
            FillExpensesPageInfo();

            if (_currentTimeStamp != null)
            {
                ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
                ClockIn.Content = "Clock Out";
            }
        }

        private void FillMainPageInfo()
        {
            hellotxtBlock.Text = "Hello " + App.ViewModel.User._username;
            datetxtBlock.Text = "Today is: " + " " + DateTime.Now.ToString("MMMM dd yyyy");
            if (App.ViewModel.User._currentLog != null)
                CurrentLogTotalTxtBlock.Text = "Current Log's total: " + App.ViewModel.User._currentLog._totalAmount;
        }

        private void FillHoursPageInfo()
        {
            if (App.ViewModel.User._hourTimeStamps.Count > 0)
            {
                ListOfHours.ItemsSource =
                    App.ViewModel.User._hourTimeStamps.Where(
                        ts => ts.EndTime.DayOfYear > DateTime.Now.DayOfYear - 7 && ts.IsFinishedTimeStamp);
                _currentTimeStamp = new Timestamps().GetCurrentTimeStamp(App.ViewModel.User._hourTimeStamps);
                TotalHoursLoggedForThisWeek.Text =
                     new Timestamps().TotalHoursAndMinutes(App.ViewModel.User._hourTimeStamps);
            }
        }

        private void FillExpensesPageInfo()
        {
            if (App.ViewModel.User._currentLog != null)
            {
                CurrentExpenseLogTxtBlock.Text = App.ViewModel.User._currentLog._nameOfLog + ".log";
                CurrentLogTotalTxtBlock.Text = "Current Log's total: " + App.ViewModel.User._currentLog._totalAmount;
                ListOfExpenses.Items.Clear();
                foreach (Expense expense in App.ViewModel.User._currentLog._ListOfExpenses)
                {
                    ListOfExpenses.Items.Add(expense);
                }
            }
        }

        private void ClockIn_Click(object sender, RoutedEventArgs e)
        {
            Button clockIn = sender as Button;
            if (clockIn != null)
            {
                if (clockIn.Content.Equals("Clock In"))
                {
                    ClockInHours();
                    App.GpsModel.GeoCoordinateWatcher.Start();
                }
                else
                {
                    ClockOutHours();
                    App.GpsModel.Stop();
                }
            }

        }

        private void ListOfHours_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void ClockInHours()
        {
            ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 255, 0, 0));
            ClockIn.Content = "Clock Out";
            //start timer and save start time
            _currentTimeStamp = new Timestamps(DateTime.Now);
            App.ViewModel.User.NewTimeStamp(_currentTimeStamp);
        }

        private void ClockOutHours()
        {
            ClockIn.Content = "Clock In";
            ClockIn.Background = new SolidColorBrush(Color.FromArgb(255, 0, 200, 0));
            //End timer and save end time
            _currentTimeStamp.EndTime = DateTime.Now;
            //save total time
            App.ViewModel.User._hourTimeStamps.Where(
                                               ts => ts.StartTime == _currentTimeStamp.StartTime).Last().EndTime =
                                               _currentTimeStamp.EndTime;
            App.ViewModel.WcfConnection.SaveTimeAsync(App.ViewModel.User.Id, _currentTimeStamp.StartTime, _currentTimeStamp.EndTime);
            //display to page
            TotalHoursLoggedForThisWeek.Text =
                new Timestamps().TotalHoursAndMinutes(App.ViewModel.User._hourTimeStamps);
            _currentTimeStamp = null;
        }

        private void OpenExpensesLog_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Expenses.xaml", UriKind.Relative));
        }

        private void NewExpense_Click(object sender, RoutedEventArgs e)
        {
            if (App.ViewModel.User._currentLog != null)
            {
                ErrorNoCurrentExptxt.Text = "";
                NavigationService.Navigate(new Uri("/CreateObjectXaml/CreateExpensePage.xaml", UriKind.Relative));
            }
            else
            {
                ErrorNoCurrentExptxt.Text = "You must open a log";
            }
        }

        private void Thread_Click(object sender, RoutedEventArgs e)
        {
            var thread = sender as StackPanel;

            if (thread != null)
            {
                var model = thread.DataContext as ThreadInfoViewModel;

                if (model != null)
                    App.ViewModel.SetCurrentThread(model.ThreadId);
            }
        }

        public void PostLoadCompleted(object sender, EventArgs args)
        {
            NavigationService.Navigate(new Uri("/ForumThreadPage.xaml", UriKind.Relative));
        }

        private void GeoCoordinateWatcherPositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
        {
            Dispatcher.BeginInvoke(() =>
            {

                App.GpsModel.UpdateLocation(e);

                txtTotalMile.Text = App.GpsModel.TotalMileage.ToString();


            });

            var latitude = e.Position.Location.Latitude;
            var longitude = e.Position.Location.Longitude;

            var location = new Location { Latitude = latitude, Longitude = longitude };
            bingMap.SetView(location, bingMap.ZoomLevel);
            bingMap.LocationToViewportPoint(location);
            currentLocation.Location = location;
            OriginLocation.Location = location;

        }

        private void PublishThreadButton_Click(object sender, RoutedEventArgs e)
        {
            LocationData location = null;

            if (App.GpsModel.CurrentLocation != null)
                location = new LocationData
                {
                    Latitude = App.GpsModel.CurrentLocation.Latitude,
                    Longitude = App.GpsModel.CurrentLocation.Longitude
                };

            App.ViewModel.WcfConnection.PublishThreadAsync(App.ViewModel.User.Id, ThreadTitle.Text, ThreadContent.Text, location);
        }

        private void allTimeStampButtons_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/TimeStampViewer.xaml", UriKind.Relative));
        }
    }
}